﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;
using System.Web.Configuration;

namespace Job.Core
{
    public class ConfigHelper
    {
        /// <summary>
        /// 获取配置文件中的值
        /// </summary>
        /// <param name="strConfigKey"></param>
        /// <returns></returns>
        public static string GetConfigValue(string strConfigKey)
        {
            return ConfigurationManager.AppSettings[strConfigKey].ToString();
        }

        /// <summary>
        /// 获取配置文件中连接字符串的值
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetConnectionString(string strKey)
        {
            return ConfigurationManager.ConnectionStrings[strKey].ToString();
        }

        public static string[] GetConfigValue(string[] strConfigKeys)
        {
            string[] strConfigValues = new string[strConfigKeys.Length];
            for (int i = 0; i < strConfigKeys.Length; i++)
            {
                strConfigValues[i] = ConfigurationManager.AppSettings[strConfigKeys[i]].ToString();
            }
            return strConfigValues;
        }

        public static void SetConfigValue(string strConfigKey, string strConfigValue)
        {
            string strConfigPath = HttpContext.Current.Request.CurrentExecutionFilePath;
            strConfigPath = strConfigPath.Substring(0, strConfigPath.LastIndexOf("/"));
            Configuration config = WebConfigurationManager.OpenWebConfiguration(strConfigPath);
            try
            {
                KeyValueConfigurationElement configElement = (KeyValueConfigurationElement)config.AppSettings.Settings[strConfigKey];
                configElement.Value = strConfigValue;
                config.Save();
            }
            catch
            {
                throw new Exception("修改" + strConfigKey + "配置节点值出错");
            }
        }

        public static void SetConfigValue(string[] strConfigKeys, string[] strConfigValues)
        {
            string strConfigPath = HttpContext.Current.Request.CurrentExecutionFilePath;
            strConfigPath = strConfigPath.Substring(0, strConfigPath.LastIndexOf("/"));
            Configuration config = WebConfigurationManager.OpenWebConfiguration(strConfigPath);
            try
            {
                for (int i = 0; i < strConfigKeys.Length; i++)
                {
                    KeyValueConfigurationElement configElement = (KeyValueConfigurationElement)config.AppSettings.Settings[strConfigKeys[i]];
                    configElement.Value = strConfigValues[i];
                }
                config.Save();
            }
            catch
            {
                throw new Exception("修改配置节点值出错");
            }
        }
    }
}
